import Vuex from 'vuex';
import $ from '$';
interface IState {
  timesList: any[];
  planInfo: any;
  classData: any; //课次数据
  prepareData: any; //备课数据
  directClass: any; //直接备课
  directData: any; //直接备课存在数据
  handoutId: any;
  formData: object; //作业表单提交
  directType: any; //直接备课判断是否为上传
  filePath: any; //直接备课判断是否为上传
}

/* 手动添加课次 */
const __manualAddition = async (commit, planInfo, type, sortNum) => {
  let nodes: any[] = type === 1 ? [
    { label: '次数', type: 'number', key: 'sumTimes', min: 1, step: 1, strictly: true, rule: [{ required: true, message: '请输入次数' }] },
    { label: '课时', type: 'number', key: 'period', min: 1, step: 1, strictly: true, rule: [{ required: true, message: '请输入课时数' }] }
  ] : [
    { label: '名称', default: type === 2 ? null : '阶段测试', type: 'input', key: 'indexName', min: 1, step: 1, strictly: true, rule: [{ required: true, message: '请输入名称' }] },
    { label: '课时', type: 'number', key: 'period', min: 1, step: 1, strictly: true, rule: [{ required: true, message: '请输入课时数' }] },
    { label: '重难点', type: 'textarea', key: 'difficultPoint' }
  ];
  let title = `${type === 1 ? '批量' : ''}添加课次`;
  let formGroup = await $.modal.create({ title, width: 400, zIndex: 2015, props: { nodes } });

  let url = `/admin/teachTimes/${type === 1 ? 'batchSave' : 'saveOrUpdate'}`
  let res = await $.http.post(url, Object.assign({ planId: planInfo.id, sortNum }, formGroup));
  res.result && $.emitter.emit('class-times-change');
}

export default new Vuex.Store<IState>({
  state: {
    timesList: [],
    planInfo: {},
    classData: null,
    prepareData: {},
    directClass: false,
    directData: null,
    handoutId: null,
    formData: {},
    directType: null,
    filePath: ''
  },

  mutations: {
    set_plan_info: (state, payload) => state.planInfo = payload,
    set_times_list: (state, payload) => state.timesList = payload,
    edit_times: (state, payload) => state.timesList = state.timesList.map(data => data.id === payload.id ? { ...data, ...payload } : data),
    delete_times: (state, payload) => state.timesList = state.timesList.filter(({ id }) => id !== payload),
    set_class_data: (state, payload) => state.classData = payload,
    set_prepare_data: (state, payload) => state.prepareData = payload,
    set_direct_class: (state, payload) => state.directClass = payload,
    set_direct_data: (state, payload) => state.directData = payload,
    set_handout_id: (state, payload) => state.handoutId = payload,
    set_form: (state, payload) => state.formData = payload,
    set_direct_type: (state, payload) => state.directType = payload,
    set_file_path: (state, payload) => state.filePath = payload,
  },

  actions: {
    add_times: ({ commit, state }, { type, index }) => __manualAddition(commit, state.planInfo, type, index),
  }
})
